const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let account = req.body.account;
	let id = req.body.id;
	let name = req.body.name;
	let department = req.body.department;
	let password = req.body.password;
	let able = req.body.able;
	let type = req.body.type;

	if (id == undefined) {
		sendResponse('error','没有选择id', null, res);
		return;
	}

	let editSql = '';
	let params = [];

	if (name != undefined) {
		editSql += 'name = ?, ';
		params.push(name);
	}

	if (department != undefined) {
		editSql += 'department = ?, ';
		params.push(department);
	}

	if (password != undefined) {
		editSql += 'password = ?, ';
		params.push(password);
	}

	if (type != undefined) {
		editSql += 'type = ?, ';
		params.push(type);
	}
	
	if (able != undefined) {
		editSql += 'able = ?, ';
		params.push(able);
	}

	params.push(id);

	if (editSql == '') {
		sendResponse('error','没有修改内容', null, res);
		return;
	} else {
		editSql = editSql.slice(0, -2);
	}


	let sql = 'UPDATE clerk SET ' + editSql + ' WHERE id = ?';

	pool.getConnection(function(err, connection) {
		if (err) { 
			sendResponse('error','数据库内部错误', null, res);
			return;
		}
		connection.query(sql, params, function (error, rows, fields) {

			connection.release();

			if (error) { 
				if (error.code = "ER_DUP_ENTRY") {
					sendResponse('error','修改重复，请检查', null, res);
					return;
				} else {
					sendResponse('error','数据库内部错误', null, res);
					return;
				}
			} else {
				sendResponse('ok','修改成功', null, res);
				return;
			}

		})	

	});

}